package com.controller.retrieval;

import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;


import org.apache.commons.io.FileUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.ServletActionContext;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

import com.table.distance;
import com.util.connection.ConnectionManager;

import java.sql.*;
import java.util.ArrayList;

public class GaborImageUpload {
	private File userImage;
	private String userImageContentType;
    private String userImageFileName;
    
    private HttpServletRequest servletRequest;
    HttpServletRequest request=ServletActionContext.getRequest();  

	public String execute() {
		Connection conn = null;
		   Statement stmt = null;
		
		try {
			 conn = ConnectionManager.getConnectionGabor();
             stmt = conn.createStatement();
             String max_img_id ="";
		      String sql = "select max(img_id)+1 max_img_id from gb_pw_mean_org";
		      ResultSet rs = stmt.executeQuery(sql);
		      while(rs.next()){
		           max_img_id  = rs.getString("max_img_id");
		       }
		       rs.close();
		       
            //String filePath = servletRequest.getSession().getServletContext().getRealPath("C:/image_retrieval_system/");
           // System.out.println("Server path:" + filePath);
            //File fileToCreate = new File("C:/image_retrieval_system/", this.userImageFileName);
		    
		       File img_file = new File("C:\\image_retrieval_system\\img.jpg");
		       File txt_file = new File("C:\\image_retrieval_system\\feature_value.txt");
		       
	    		if(img_file.delete()&&txt_file.delete()){
	    			//System.out.println(img_file.getName() + " is deleted!");
	    			//System.out.println(txt_file.getName() + " is deleted!");
	    		}else{
	    			System.out.println("Delete operation is failed.");
	    		}   
			File fileToCreate = new File("C:/image_retrieval_system/", "img_temp.jpg");
            FileUtils.copyFile(this.userImage, fileToCreate);
            fileToCreate = new File("C:/JavaWork/.metadata/.me_tcat/webapps/allimages", max_img_id+".jpg");
            FileUtils.copyFile(this.userImage, fileToCreate);
            
            BufferedImage originalImage = ImageIO.read(new File("C:/image_retrieval_system/img_temp.jpg"));
    		int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
     
    		BufferedImage resizeImageJpg = resizeImage(originalImage, type);
    		ImageIO.write(resizeImageJpg, "jpg", new File("C:/image_retrieval_system/img.jpg")); 
    		
            try {
                Runtime runtime = Runtime.getRuntime();
                //Process p = Runtime.getRuntime().exec("cmd /c start "+"D:\\image_retrieval_system\\calculate_feature.exe");
                Process p = Runtime.getRuntime().exec("C:\\image_retrieval_system\\calculate_feature.exe");
                p.waitFor();
                
                String sCurrentLine;
                
                BufferedReader  br = new BufferedReader(new FileReader("C:\\image_retrieval_system\\feature_value.txt"));
     
                Statement batch_stmt = conn.createStatement();
    			while ((sCurrentLine = br.readLine()) != null) {
    				String[] str_array=sCurrentLine.split(",");
    				String query = "insert into gb_original(img_id, sub_img_id,pw_mean,pw_std,img_name) values("
    		            + max_img_id + "," +str_array[1]+","+str_array[3]+","+str_array[4]+",'"+max_img_id+".jpg')";
    				batch_stmt.addBatch(query);
    			}
    			br.close();
    			batch_stmt.executeBatch();
    			batch_stmt.close();
    			
    			Statement Insert_stmt = conn.createStatement();
    			
    			String query="insert into gb_pw_mean_org  ( "+
					" select img_id, "+
    				" round(sum(if(sub_img_id=1,pw_mean,0)),4) pw_mean1, "+
    				" round(sum(if(sub_img_id=2,pw_mean,0)),4) pw_mean2, "+
    				" round(sum(if(sub_img_id=3,pw_mean,0)),4) pw_mean3, "+
    				" round(sum(if(sub_img_id=4,pw_mean,0)),4) pw_mean4, "+
    				" round(sum(if(sub_img_id=5,pw_mean,0)),4) pw_mean5, "+
    				" round(sum(if(sub_img_id=6,pw_mean,0)),4) pw_mean6, "+
    				" round(sum(if(sub_img_id=7,pw_mean,0)),4) pw_mean7, "+
    				" round(sum(if(sub_img_id=8,pw_mean,0)),4) pw_mean8, "+
    				" round(sum(if(sub_img_id=9,pw_mean,0)),4) pw_mean9, "+
    				" round(sum(if(sub_img_id=10,pw_mean,0)),4) pw_mean10, "+
    				" round(sum(if(sub_img_id=11,pw_mean,0)),4) pw_mean11, "+
    				" round(sum(if(sub_img_id=12,pw_mean,0)),4) pw_mean12, "+
    				" round(sum(if(sub_img_id=13,pw_mean,0)),4) pw_mean13, "+
    				" round(sum(if(sub_img_id=14,pw_mean,0)),4) pw_mean14, "+
    				" round(sum(if(sub_img_id=15,pw_mean,0)),4) pw_mean15, "+
    				" round(sum(if(sub_img_id=16,pw_mean,0)),4) pw_mean16, "+
    				" round(sum(if(sub_img_id=17,pw_mean,0)),4) pw_mean17, "+
    				" round(sum(if(sub_img_id=18,pw_mean,0)),4) pw_mean18, "+
    				" round(sum(if(sub_img_id=19,pw_mean,0)),4) pw_mean19, "+
    				" round(sum(if(sub_img_id=20,pw_mean,0)),4) pw_mean20, "+
    				" round(sum(if(sub_img_id=21,pw_mean,0)),4) pw_mean21, "+
    				" round(sum(if(sub_img_id=22,pw_mean,0)),4) pw_mean22, "+
    				" round(sum(if(sub_img_id=23,pw_mean,0)),4) pw_mean23, "+
    				" round(sum(if(sub_img_id=24,pw_mean,0)),4) pw_mean24, "+
    				" img_name  "+
    				" from gb_original  where img_id="+max_img_id +
    				" group by img_id,img_name )";
    			 
    			Insert_stmt.addBatch(query);
    			
    			query=
    			"insert into gb_pw_std_org ( " +
    			" select img_id, " +
    			" round(sum(if(sub_img_id=1,pw_std,0)),4) pw_std1, " +
    			" round(sum(if(sub_img_id=2,pw_std,0)),4) pw_std2, " +
    			" round(sum(if(sub_img_id=3,pw_std,0)),4) pw_std3, " +
    			" round(sum(if(sub_img_id=4,pw_std,0)),4) pw_std4, " +
    			" round(sum(if(sub_img_id=5,pw_std,0)),4) pw_std5, " +
    			" round(sum(if(sub_img_id=6,pw_std,0)),4) pw_std6, " +
    			" round(sum(if(sub_img_id=7,pw_std,0)),4) pw_std7, " +
    			" round(sum(if(sub_img_id=8,pw_std,0)),4) pw_std8, " +
    			" round(sum(if(sub_img_id=9,pw_std,0)),4) pw_std9, " +
    			" round(sum(if(sub_img_id=10,pw_std,0)),4) pw_std10, " +
    			" round(sum(if(sub_img_id=11,pw_std,0)),4) pw_std11, " +
    			" round(sum(if(sub_img_id=12,pw_std,0)),4) pw_std12, " +
    			" round(sum(if(sub_img_id=13,pw_std,0)),4) pw_std13, " +
    			" round(sum(if(sub_img_id=14,pw_std,0)),4) pw_std14, " +
    			" round(sum(if(sub_img_id=15,pw_std,0)),4) pw_std15, " +
    			" round(sum(if(sub_img_id=16,pw_std,0)),4) pw_std16, " +
    			" round(sum(if(sub_img_id=17,pw_std,0)),4) pw_std17, " +
    			" round(sum(if(sub_img_id=18,pw_std,0)),4) pw_std18, " +
    			" round(sum(if(sub_img_id=19,pw_std,0)),4) pw_std19, " +
    			" round(sum(if(sub_img_id=20,pw_std,0)),4) pw_std20, " +
    			" round(sum(if(sub_img_id=21,pw_std,0)),4) pw_std21, " +
    			" round(sum(if(sub_img_id=22,pw_std,0)),4) pw_std22, " +
    			" round(sum(if(sub_img_id=23,pw_std,0)),4) pw_std23, " +
    			" round(sum(if(sub_img_id=24,pw_std,0)),4) pw_std24, " +
    			" img_name " +
    			" from gb_original where img_id="+max_img_id +
    			" group by img_id,img_name " +
    			") " ;
    			
    			Insert_stmt.addBatch(query);
    			Insert_stmt.executeBatch();
    			
    			Statement dist_stmt = conn.createStatement();
    			 String sql_insrt = "insert into gb_pw_mean_std_dist(query_im_id,data_im_id,distance,img_name)(";
                 sql_insrt = sql_insrt +
                     "select t1.img_id query_im_id,t2.img_id data_im_id,  "
                                    + " sqrt( "
                                    + " (t1.pw_mean1-t2.pw_mean1)*(t1.pw_mean1-t2.pw_mean1)+(t1.pw_mean2-t2.pw_mean2)*(t1.pw_mean2-t2.pw_mean2)+(t1.pw_mean3-t2.pw_mean3)*(t1.pw_mean3-t2.pw_mean3)+  "
                                    + " (t1.pw_mean4-t2.pw_mean4)*(t1.pw_mean4-t2.pw_mean4)+(t1.pw_mean5-t2.pw_mean5)*(t1.pw_mean5-t2.pw_mean5)+(t1.pw_mean6-t2.pw_mean6)*(t1.pw_mean6-t2.pw_mean6)+ "
                                    + " (t1.pw_mean7-t2.pw_mean7)*(t1.pw_mean7-t2.pw_mean7)+(t1.pw_mean8-t2.pw_mean8)*(t1.pw_mean8-t2.pw_mean8)+(t1.pw_mean9-t2.pw_mean9)*(t1.pw_mean9-t2.pw_mean9)+ "
                                    + " (t1.pw_mean10-t2.pw_mean10)*(t1.pw_mean10-t2.pw_mean10)+(t1.pw_mean11-t2.pw_mean11)*(t1.pw_mean11-t2.pw_mean11)+(t1.pw_mean12-t2.pw_mean12)*(t1.pw_mean12-t2.pw_mean12)+ "
                                    + " (t1.pw_mean13-t2.pw_mean13)*(t1.pw_mean13-t2.pw_mean13)+(t1.pw_mean14-t2.pw_mean14)*(t1.pw_mean14-t2.pw_mean14)+(t1.pw_mean15-t2.pw_mean15)*(t1.pw_mean15-t2.pw_mean15)+ "
                                    + " (t1.pw_mean16-t2.pw_mean16)*(t1.pw_mean16-t2.pw_mean16)+(t1.pw_mean17-t2.pw_mean17)*(t1.pw_mean17-t2.pw_mean17)+(t1.pw_mean18-t2.pw_mean18)*(t1.pw_mean18-t2.pw_mean18)+ "
                                    + " (t1.pw_mean19-t2.pw_mean19)*(t1.pw_mean19-t2.pw_mean19)+(t1.pw_mean20-t2.pw_mean20)*(t1.pw_mean20-t2.pw_mean20)+(t1.pw_mean21-t2.pw_mean21)*(t1.pw_mean21-t2.pw_mean21)+ "
                                    + " (t1.pw_mean22-t2.pw_mean22)*(t1.pw_mean22-t2.pw_mean22)+(t1.pw_mean23-t2.pw_mean23)*(t1.pw_mean23-t2.pw_mean23)+(t1.pw_mean24-t2.pw_mean24)*(t1.pw_mean24-t2.pw_mean24)+ "
                                    + " (t1.pw_std1-t2.pw_std1)*(t1.pw_std1-t2.pw_std1)+(t1.pw_std2-t2.pw_std2)*(t1.pw_std2-t2.pw_std2)+(t1.pw_std3-t2.pw_std3)*(t1.pw_std3-t2.pw_std3)+ "
                                    + " (t1.pw_std4-t2.pw_std4)*(t1.pw_std4-t2.pw_std4)+(t1.pw_std5-t2.pw_std5)*(t1.pw_std5-t2.pw_std5)+(t1.pw_std6-t2.pw_std6)*(t1.pw_std6-t2.pw_std6)+ "
                                    + " (t1.pw_std7-t2.pw_std7)*(t1.pw_std7-t2.pw_std7)+(t1.pw_std8-t2.pw_std8)*(t1.pw_std8-t2.pw_std8)+(t1.pw_std9-t2.pw_std9)*(t1.pw_std9-t2.pw_std9)+ "
                                    + " (t1.pw_std10-t2.pw_std10)*(t1.pw_std10-t2.pw_std10)+(t1.pw_std11-t2.pw_std11)*(t1.pw_std11-t2.pw_std11)+(t1.pw_std12-t2.pw_std12)*(t1.pw_std12-t2.pw_std12)+ "
                                    + " (t1.pw_std13-t2.pw_std13)*(t1.pw_std13-t2.pw_std13)+(t1.pw_std14-t2.pw_std14)*(t1.pw_std14-t2.pw_std14)+(t1.pw_std15-t2.pw_std15)*(t1.pw_std15-t2.pw_std15)+ "
                                    + " (t1.pw_std16-t2.pw_std16)*(t1.pw_std16-t2.pw_std16)+(t1.pw_std17-t2.pw_std17)*(t1.pw_std17-t2.pw_std17)+(t1.pw_std18-t2.pw_std18)*(t1.pw_std18-t2.pw_std18)+ "
                                    + " (t1.pw_std19-t2.pw_std19)*(t1.pw_std19-t2.pw_std19)+(t1.pw_std20-t2.pw_std20)*(t1.pw_std20-t2.pw_std20)+(t1.pw_std21-t2.pw_std21)*(t1.pw_std21-t2.pw_std21)+ "
                                    + " (t1.pw_std22-t2.pw_std22)*(t1.pw_std22-t2.pw_std22)+(t1.pw_std23-t2.pw_std23)*(t1.pw_std23-t2.pw_std23)+(t1.pw_std24-t2.pw_std24)*(t1.pw_std24-t2.pw_std24) "
                                    + " ) val,t2.img_name "
                                    + " from  "
                                    + " ( "
                                    + " select m.img_id, m.pw_mean1,m.pw_mean2,m.pw_mean3,m.pw_mean4,m.pw_mean5,m.pw_mean6,m.pw_mean7,m.pw_mean8,m.pw_mean9,m.pw_mean10, "
                                    + " m.pw_mean11,m.pw_mean12,m.pw_mean13,m.pw_mean14,m.pw_mean15,m.pw_mean16,m.pw_mean17,m.pw_mean18,m.pw_mean19,m.pw_mean20,m.pw_mean21,m.pw_mean22, "
                                    + " m.pw_mean23,m.pw_mean24, "
                                    + " s.pw_std1,s.pw_std2,s.pw_std3,s.pw_std4,s.pw_std5,s.pw_std6,s.pw_std7,s.pw_std8,s.pw_std9, "
                                    + " s.pw_std10,s.pw_std11,s.pw_std12,s.pw_std13,s.pw_std14,s.pw_std15,s.pw_std16,s.pw_std17,s.pw_std18, "
                                    + " s.pw_std19,s.pw_std20,s.pw_std21,s.pw_std22,s.pw_std23,s.pw_std24,s.img_name "
                                    + " from gb_pw_mean_org m,gb_pw_std_org s "
                                    + " where s.img_id=m.img_id  and  m.img_id= " + max_img_id
                                    + " )t1, "
                                    + " ( "
                                    + " select m.img_id, m.pw_mean1,m.pw_mean2,m.pw_mean3,m.pw_mean4,m.pw_mean5,m.pw_mean6,m.pw_mean7,m.pw_mean8,m.pw_mean9,m.pw_mean10, "
                                    + " m.pw_mean11,m.pw_mean12,m.pw_mean13,m.pw_mean14,m.pw_mean15,m.pw_mean16,m.pw_mean17,m.pw_mean18,m.pw_mean19,m.pw_mean20,m.pw_mean21,m.pw_mean22, "
                                    + " m.pw_mean23,m.pw_mean24, "
                                    + " s.pw_std1,s.pw_std2,s.pw_std3,s.pw_std4,s.pw_std5,s.pw_std6,s.pw_std7,s.pw_std8,s.pw_std9, "
                                    + " s.pw_std10,s.pw_std11,s.pw_std12,s.pw_std13,s.pw_std14,s.pw_std15,s.pw_std16,s.pw_std17,s.pw_std18, "
                                    + " s.pw_std19,s.pw_std20,s.pw_std21,s.pw_std22,s.pw_std23,s.pw_std24,s.img_name "
                                    + " from gb_pw_mean_org m,gb_pw_std_org s "
                                    + " where s.img_id=m.img_id  "
                                    + " )t2 ";

                 sql_insrt = sql_insrt + ")";
                 dist_stmt.addBatch(sql_insrt);
                 dist_stmt.executeBatch();
                 
                 ServletActionContext.getRequest().getSession().setAttribute("current_gb_query", max_img_id);
                 String sel_sql = "select data_im_id,distance from gb_pw_mean_std_dist where query_im_id=" +max_img_id + "  order by distance LIMIT  0 , 25";
                 ResultSet rs_img = stmt.executeQuery(sel_sql);
                 ArrayList imgList = new ArrayList();
                 
   		      while(rs_img.next()){
   		    	distance imgDistObj=new distance();
   		    	imgDistObj.setData_im_id(rs_img.getString("data_im_id"));
   		    	imgList.add(imgDistObj);
   		       }
   		      rs_img.close();
   		     request.setAttribute("imgList", imgList);
   		      
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            
        } catch(SQLException se){
            se.printStackTrace();
         }catch(Exception e){
            e.printStackTrace();
         }finally{
            try{
               if(stmt!=null)
                  conn.close();
            }catch(SQLException se){
            }
            try{
               if(conn!=null)
                  conn.close();
            }catch(SQLException se){
               se.printStackTrace();
            }
         }
         
        return "success";

	}
	
	private static final int IMG_WIDTH = 128;
	private static final int IMG_HEIGHT = 128;
	
	private static BufferedImage resizeImage(BufferedImage originalImage, int type){
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();
	 
		return resizedImage;
	    }
	
    public File getUserImage() {
		return userImage;
	}


	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}


	public String getUserImageContentType() {
		return userImageContentType;
	}


	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}


	public String getUserImageFileName() {
		return userImageFileName;
	}


	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}


	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}


	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}


	
    
    
	
}
